package xyz.yuelai.blog.controller;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import xyz.yuelai.blog.entity.Article;
import xyz.yuelai.blog.entity.ArticleBrief;
import xyz.yuelai.blog.entity.ArticleCategory;
import xyz.yuelai.blog.entity.ArticleDetail;
import xyz.yuelai.blog.service.IArticleCategoryService;
import xyz.yuelai.blog.service.IArticleDetailService;
import xyz.yuelai.blog.service.IArticleService;
import xyz.yuelai.blog.util.PageInfoUtil;

@Controller
@RequestMapping("/back")
public class BackController {

	@Resource
	private IArticleService articleService;
	@Resource
	private IArticleDetailService articleDetailService;
	@Resource
	private IArticleCategoryService articleCategoryService;

	/**
	 * 后台登陆首页
	 * 
	 * @param page
	 *            页码
	 * @param model
	 * @return
	 */
	@RequestMapping("/index")
	public String index(Integer page, Model model) {
		if (page == null || page <= 0) {
			page = 1;
		}
		PageInfoUtil pageInfoUtil = new PageInfoUtil();
		pageInfoUtil.setCurrentPage(page);
		Map<String, Object> conditionMap = new HashMap<>();
		conditionMap.put("orderby", "id");
		conditionMap.put("sort", "desc");
		List<ArticleBrief> briefs = articleService.getArticleBriefList(pageInfoUtil, conditionMap);
		model.addAttribute("briefs", briefs);
		model.addAttribute("page", pageInfoUtil);
		return "/back/index";
	}

	/**
	 * 新增文章，编辑文章页面跳转入口
	 * 
	 * @param type
	 *            新增还是编辑
	 * @param id
	 *            编辑指定文章id
	 * @param model
	 * @return
	 */
	@RequestMapping("/article-{type}")
	public String article(@PathVariable String type, Integer id, Model model) {
		if (type.equals("edit")) {
			List<ArticleCategory> categorys = articleCategoryService.getArticleCategoryList(null,
					new HashMap<String, Object>());
			model.addAttribute("categorys", categorys);
			ArticleDetail detail = articleService.getArticleDetail(id);
			ArticleBrief brief = articleService.getArticleBrief(id);
			model.addAttribute("detail", detail);
			model.addAttribute("brief", brief);
			model.addAttribute("type", "edit");
		} else if (type.equals("add")) {
			List<ArticleCategory> categorys = articleCategoryService.getArticleCategoryList(null,
					new HashMap<String, Object>());
			model.addAttribute("categorys", categorys);
			model.addAttribute("type", "add");
		} else if (type.equals("delete")) {
			articleService.deleteArticle(id);
			return "/back/index";
		}
		return "/back/article-add";
	}

	@RequestMapping("/articleSubmit-{type}")
	public String articleSubmit(@PathVariable String type, ArticleDetail detail, ArticleBrief brief,
			ArticleCategory category, String dbImg, MultipartFile image, Model model, HttpServletRequest request) {
		String dbImgPath = "";
		System.out.println("image=" + image);
		if (image != null && !image.isEmpty()) {
			try {
				String realPath = request.getServletContext().getRealPath("/");
				Date date = new Date();
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");
				String datePath = sdf.format(date);
				String path = "/static/images/" + datePath;
				File dir = new File(realPath + path);
				if (!dir.exists()) {
					dir.mkdirs();
				}
				dbImgPath = path + new Date().getTime() + new Random().nextInt(Integer.MAX_VALUE) + ".jpg";
				File f = new File(realPath + dbImgPath);
				image.transferTo(f);
				brief.setImg(dbImgPath);
			} catch (IllegalStateException | IOException e) {
				e.printStackTrace();
			}
		} else {
			brief.setImg(dbImg);
		}
		if (type.equals("add")) {
			Integer maxID = articleService.getMaxID();
			brief.setId(maxID + 1);
			brief.setArticleCategory(category);
			brief.setPublishTime(new Date());
			brief.setReadNum(0);
			if (detail.getAllowComments() == null) {
				detail.setAllowComments(0);
			}
			if (brief.getStatus() == null) {
				brief.setStatus(0);
			}
			Article article = new Article(brief, detail);
			articleService.saveArticle(article);

			System.out.println(detail);
			System.out.println(brief);

		} else if (type.equals("edit")) {
			if (detail.getAllowComments() == null) {
				detail.setAllowComments(0);
			}
			if (brief.getStatus() == null) {
				brief.setStatus(0);
			}
			brief.setArticleCategory(category);
			System.out.println(detail);
			System.out.println(brief);
			Article article = new Article(brief, detail);
			articleService.updateArticle(article);
		}

		return "redirect:/back/index.html";
	}

}
